# coding: utf-8

import tornado
import datetime
from bson import ObjectId
from handlers.base import BaseHandler

FEMALE_AVATAR_URL = 'http://7xlaxq.com1.z0.glb.clouddn.com/female.png'
MALE_AVATAR_URL = 'http://7xlaxq.com1.z0.glb.clouddn.com/male.png'
DEFAULTROLE_AVATAR = "http://7xlaxq.com1.z0.glb.clouddn.com/me.png"

class FocusOn(BaseHandler):
    @tornado.gen.coroutine
    def get(self):
        """
        获取user关注的人的列表
        :return:
        """
        try:
            uid = self.get_query_argument('uid')
        except Exception as err:
            self.response_msg(400, '获取用户信息出错')
            return
        try:
            roles = self.db.HMRoles.find({'user': uid},
                                         {'_id':1,"nickname":1,"isDefault":1,"avatar":1}).sort('isDefault',-1)
            results = []
            while(yield roles.fetch_next):
                role = roles.next_object()
                role['objectId'] = str(role['_id'])
                del role['_id']
                results.append(role)
            self.response_msg(200, '获取数据成功', results)
        except Exception as e:
            results = []
            self.response_msg(200, '获取数据成功', results)


class RolesHandler(BaseHandler):
    @tornado.gen.coroutine
    def get(self):
        """
        通过rid查询role的基本信息
        :return:
        """
        if 'rid' in self.request.arguments:
            rid = self.get_query_argument('rid')
        else:
            self.response_msg(400, '获取用户角色ID失败')
            return
        try:
            role = yield self.db.HMRoles.find_one({'_id': ObjectId(rid)},
                                                 {'_id':1,"nickname":1,"isDefault":1,'weight':1,"height":1,"avatar":1,"birthday":1})

            #如果有返回
            if role:
                role['objectId'] = str(role['_id'])
                role['birthday'] = str(role['birthday'])
                del role['_id']
                self.response_msg(200, '查询成功', role)
            else:
                self.response_msg(404,"没找到用户信息")
        except Exception as e:
            self.response_msg(400, '数据库查询过程出错,错误为'+str(e))





    @tornado.gen.coroutine
    def post(self):
        """
        如果有rid就是修改role，如果没有rid就是创建一个新的role,返回roleId
        :return:
        """
        if 'uid' in self.request.arguments:
            uid = self.get_argument('uid')
        else:
            self.response_msg(400, '获取用户角色ID失败')
            return
        try:
            uid = self.get_argument('uid')
            gender = self.get_argument('gender')
            nickname = self.get_argument('roleName')
            height = self.get_argument('height')
            weight = self.get_argument('weight')
            birthday = self.get_argument('birthday')
            isNewTemplate = self.get_argument('isNewTemplate')
            templateName = self.get_argument('templateName')
            templateId = self.get_argument('template')
            height = int(height)
            weight = int(weight)
            birthday = datetime.datetime.strptime(birthday, '%Y-%m-%d')
        except Exception as e:
            print(e)
            self.response_msg(400, '解析参数错误')
        try:
            #如果参数表明这是一个新增加的模板,则新建模板
            if isNewTemplate == '1':
                templateSave = {}
                templateSave['user'] = uid
                templateSave['name'] = templateName
                templateSave['sex'] = gender
                templateSave['sort'] = 99
                templateSave['avatar'] = getAvatarBySex(gender)
                templateSave['isTop'] = True
                templateSave['chooseNumber'] = 1
                templateSave['isDefault'] = False
                template = yield self.db.HMRoleTemplates.save(templateSave)
            #开始新建一个角色
            roleInfo = {}
            roleInfo['birthday'] = birthday
            roleInfo['user'] = uid
            roleInfo['weight'] = weight
            roleInfo['height'] = height
            roleInfo['nickname'] = nickname
            roleInfo['sex'] = gender
            #关于角色图片的问题
            if templateId:
                roleInfo['avatar'] = yield self.getAvatarByTemplate(templateId)
            else:
                roleInfo['avatar'] = getAvatarBySex(gender)
            roleInfo['isDefault'] = False
            roleInfo['measureCount'] = 0
            roleInfo['healthPlan'] = []
            roleInfo['created_at'] = datetime.datetime.now()
            role = yield self.db.HMRoles.save(roleInfo)
            #完成角色信息保存
            if role:
                self.response_msg(200, '新建角色成功', {'roleId': str(role)})
            else:
                self.response_msg(400, '角色创建失败')
        except Exception as e:
            print(e)
            self.response_msg(400, '保存数据发生错误')



    #通过模板获取图片信息
    @tornado.gen.coroutine
    def getAvatarByTemplate(self,tid):
        tidInfo = yield self.db.HMRoleTemplates.find_one({'_id':ObjectId(tid)},{'avatar':1,'_id':0})
        if tidInfo:
            return tidInfo['avatar']
        else:
            return DEFAULTROLE_AVATAR

    @tornado.gen.coroutine
    def put(self, *args, **kwargs):
        #获取参数
        try:
            uid = self.get_argument('uid')
            rid = self.get_argument('rid')
        except Exception as e:
            self.response_msg(101,"获取用户信息失败")
            return

        #获取待修改信息
        try:
            nickname = self.get_argument('nickname')
            height = self.get_argument('height')
            weight = self.get_argument('weight')
            birthday = self.get_argument('birthday')

            height = int(height)
            weight = int(weight)
            birthday = datetime.datetime.strptime(birthday, '%Y-%m-%d')
        except Exception as err:
            print(err)
            self.response_msg(400, '参数错误')
            return
        try:
            #保存其他信息
            ret = yield self.db.HMRoles.update({'_id': ObjectId(rid)},
                                            {'$set': {'height': height, 'weight': weight, 'birthday': birthday,
                                                    'nickname': nickname}})
            #如果保存成功,则返回正确消息
            if ret['updatedExisting']:
                self.response_msg(200,"修改数据成功")
            else:
                self.response_msg(201,"修改失败")
        except Exception as err:
            self.response_msg(500, '修改数据错误')


    @tornado.gen.coroutine
    def delete(self, *args, **kwargs):
        """
        删除一个role
        :param args:
        :param kwargs:
        :return:
        """
        try:
            rid = self.get_argument('rid')
        except Exception as err:
            self.response_msg(400, '参数错误')
            return
        try:
            ret = yield self.db.HMRoles.remove({'_id': ObjectId(rid)})
            if ret:
                self.response_msg(200, '删除成功')
            else:
                self.response_msg(201, '删除失败')
        except Exception as err:
            self.response_msg(400, '删除失败')


class RolesTemplatesHandler(BaseHandler):
    @tornado.gen.coroutine
    def get(self):
        try:
            uid = self.get_query_argument('uid')
        except Exception as err:
            self.response_msg(400, '获取用户信息失败')
            return
        try:
            results = []
            #查询所有默认的角色模板和该用户自建的模板
            templates = self.db.HMRoleTemplates.find({'$or':[{'user': uid},
                                                            {'isDefault':True}]},
                                                    {'_id': 1,'sex':1,'name':1,"avatar":1}).sort('sort',1)
            while(yield templates.fetch_next):
                templateObj = templates.next_object()
                if templateObj:
                    templateObj['objectId'] = str(templateObj['_id'])
                    del templateObj['_id']
                    results.append(templateObj)
            #获取到了所有的模板,开始返回
            self.response_msg(200,"获取数据成功",results)
        except Exception as e:
            results = []
            self.response_msg(200,"获取数据成功",results)




class DefaultRole(BaseHandler):
    @tornado.gen.coroutine
    def get(self, *args, **kwargs):
        """
        通过uid，查询出这个用户的默认关心的role，返回roleId
        :param args:
        :param kwargs:
        :return:
        """
        try:
            uid = self.get_query_argument('uid')
        except Exception as err:
            self.response_msg(400, '获取用户参数错误')
            return
        try:
            # 获取默认关注的人
            role = yield self.db.HMRoles.find_one({'user': uid, 'isDefault': True}, {'_id': 1})
            res = {}
            if role:
                res['roleId'] = str(role['_id'])
                del role['_id']
                res['hasRoles'] = True
            else:
                # 如果没有默认关注的人，就从最选出最晚创建的人
                count = yield self.db.HMRoles.find({'user':uid}).count()
                if count > 0:
                    last_role =  self.db.HMRoles.find({'user':uid},{'_id':1}).sort('created_at', -1).limit(1)
                    while(yield last_role.fetch_next):
                        roleObj = last_role.next_object()
                        res['roleId'] = str(roleObj['_id'])
                        res['hasRoles'] = True
                else:
                    res['hasRoles'] = False
            #返回结果
            self.response_msg(200, '获取角色信息成功',res)
        except Exception as err:
            self.response_msg(500, '获取角色信息失败')



    @tornado.gen.coroutine
    def put(self, *args, **kwargs):
        """
        设置一个默认的关心role
        :param args:
        :param kwargs:
        :return:
        """
        if 'uid' in self.request.arguments and 'rid' in self.request.arguments:
            uid = self.get_argument('uid')
            rid = self.get_argument('rid')
        else:
            self.response_msg(400, '输入的参数错误')
            return
        #这里加入判断,如果在修改前存在默认角色,则先取消掉之前的默认角色
        hasDefault = yield self.db.HMRoles.find_one({'user':uid,'isDefault':True},{'_id':1})
        if hasDefault:
            #如果存在,取消掉
            updatedRes= yield self.db.HMRoles.update({'_id':hasDefault['_id']},{'$set':{'isDefault':False}})
            #再修改本身自己的默认角色信息
        updatedResSelf = yield self.db.HMRoles.update({'_id':ObjectId(rid)},{'$set':{'isDefault':True}})
        if updatedResSelf['updatedExisting']:
            self.response_msg(200,"修改成功")
        else:
            self.response_msg(201,"修改失败");


def getAvatarBySex(sex):
    if sex == 'female':
        return FEMALE_AVATAR_URL
    else:
        return MALE_AVATAR_URL